<template>
	<view class="container">
		<view class="form">
			<uv-form labelPosition="left" :model="model" :rules="rules" ref="form">
				<view style="display: none;">
					<uv-input v-model="model.info.id" border="none">
					</uv-input>
				</view>

				<view class="label">店铺信息</view>
				<view class="item">
					<uv-form-item label="店铺LOGO" prop="info.avatar" labelWidth="100" :customStyle="itemStyle"
						borderBottom>
						<uv-upload :fileList="fileList1" name="1" multiple :maxCount="1" @afterRead="afterRead"
							@delete="deletePic"></uv-upload>
					</uv-form-item>
					<uv-form-item label="店铺名称" prop="info.shopname" labelWidth="100" :customStyle="itemStyle"
						borderBottom>
						<uv-input v-model="model.info.shopname" border="none" placeholder="请输入店铺名称">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="店铺简介" prop="info.bio" labelWidth="100" :customStyle="itemStyle" borderBottom>
						<uv-input v-model="model.info.bio" border="none" placeholder="请输入店铺简介">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="店铺区域" prop="info.area_id" labelWidth="100" :customStyle="itemStyle"
						borderBottom @click="btnAddressClick">
						<uv-input v-model="model.info.area_text" disabled disabledColor="#ffffff" placeholder="请选择店铺区域"
							border="none">
						</uv-input>
						<template v-slot:right>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item>
					<uv-form-item label="店铺描述" prop="info.description" labelWidth="100" :customStyle="itemStyle">
						<uv-input v-model="model.info.description" border="none" placeholder="请输入店铺描述">
						</uv-input>
					</uv-form-item>
				</view>

				<view class="label">企业信息</view>
				<view class="item">
					<uv-form-item label="营业执照" prop="info.image" labelWidth="100" :customStyle="itemStyle" borderBottom>
						<uv-upload :fileList="fileList2" name="2" multiple :maxCount="1" @afterRead="afterRead"
							@delete="deletePic"></uv-upload>
					</uv-form-item>
					<uv-form-item label="企业名称" prop="info.name" labelWidth="100" :customStyle="itemStyle" borderBottom>
						<uv-input v-model="model.info.name" border="none" placeholder="请输入营业执照名称">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="企业代码" prop="info.number" labelWidth="100" :customStyle="itemStyle"
						borderBottom>
						<uv-input v-model="model.info.number" border="none" placeholder="请输入社会统一信用代码" maxlength="18">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="法人姓名" prop="info.legal_person" labelWidth="100" :customStyle="itemStyle">
						<uv-input v-model="model.info.legal_person" border="none" placeholder="请输入法人姓名">
						</uv-input>
					</uv-form-item>
				</view>

				<view class="label">联系人信息</view>
				<view class="item">
					<uv-form-item label="联系人" prop="info.contact" labelWidth="100" :customStyle="itemStyle"
						borderBottom>
						<uv-input v-model="model.info.contact" border="none" placeholder="请输入联系人">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="联系电话" prop="info.mobile" labelWidth="100" :customStyle="itemStyle"
						borderBottom>
						<uv-input v-model="model.info.mobile" border="none" placeholder="请输入联系电话"
							type="number"></uv-input>
					</uv-form-item>
					<uv-form-item label="微信号" prop="info.wechat" labelWidth="100" :customStyle="itemStyle">
						<uv-input v-model="model.info.wechat" border="none" placeholder="请输入微信号">
						</uv-input>
					</uv-form-item>
				</view>

				<view class="label">密码信息</view>
				<view class="item">
					<uv-form-item label="登录密码" prop="info.password" labelWidth="100" :customStyle="itemStyle"
						borderBottom>
						<uv-input v-model="model.info.password" border="none" type="password" placeholder="请输入登录密码">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="确认登录密码" prop="info.confirm_password" labelWidth="100" :customStyle="itemStyle">
						<uv-input v-model="model.info.confirm_password" border="none" type="password"
							placeholder="请输入确认登录密码">
						</uv-input>
					</uv-form-item>
				</view>

				<view class="item">
					<uv-form-item label="企业类型" prop="info.state" labelWidth="100" :customStyle="itemStyle"
						@click="openStatePicker">
						<uv-input v-model="model.info.state_text" disabled disabledColor="#ffffff" placeholder="请选择企业类型"
							border="none">
						</uv-input>
						<template v-slot:right>
							<uv-picker ref="statePicker" :columns="stateList" @confirm="stateConfirm"></uv-picker>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-form-item>
					<view v-show="authState">
						<uv-form-item label="授权证书" prop="info.authorization_images" labelWidth="100"
							:customStyle="itemStyle">
							<uv-upload :fileList="fileList3" name="3" multiple :maxCount="5" @afterRead="afterRead"
								@delete="deletePic"></uv-upload>
						</uv-form-item>
					</view>
				</view>
			</uv-form>
		</view>
		<view class="btn">
			<uv-button text="提交" color="#fe5400" @click="submit" :customStyle="buttonCustomStyle"></uv-button>
		</view>

		<wanl-address ref='wanlAddress' @selectAddress="successSelectAddress"></wanl-address>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fileList1: [], // 头像/logo照片
				fileList2: [], // 营业执照照片
				fileList3: [], // 授权证书照片
				areaId: '', // 地区ID
				areaList: [], // 地区数据
				stateList: [
					['授权代理', '非授权贸易']
				], // 企业类型
				authState: false,
				model: {
					info: {
						id: '',
						shopname: '',
						name: '',
						number: '',
						contact: '',
						legal_person: '',
						mobile: '',
						image: '',
						wechat: '',
						avatar: '',
						bio: '',
						area_id: '',
						area_text: '',
						password: '',
						confirm_password: '',
						description: '',
						state: '',
						state_text: '',
						authorization_images: '',
					},
				},
				rules: {
					'info.shopname': {
						type: 'string',
						required: true,
						message: '请填写店铺名称',
						trigger: ['blur', 'change']
					},
					'info.name': {
						type: 'string',
						required: true,
						message: '请填写企业名称',
						trigger: ['blur', 'change']
					},
					'info.number': {
						type: 'string',
						required: true,
						message: '请输入社会统一信用代码',
						trigger: ['blur', 'change'],
						min: 18,
						max: 18,
						pattern: /^[0-9]{18}$/, // 可根据实际情况调整正则表达式
						message: '社会统一信用代码必须是18位数字'
					},
					'info.contact': {
						type: 'string',
						required: true,
						message: '请输入联系人',
						trigger: ['blur', 'change']
					},
					'info.legal_person': {
						type: 'string',
						required: true,
						message: '请输入法人姓名',
						trigger: ['blur', 'change']
					},
					'info.mobile': {
						type: 'string',
						required: true,
						message: '请输入联系电话',
						trigger: ['blur', 'change'],
						pattern: /^1[3-9]\d{9}$/, // 校验手机号码
						message: '请输入有效的手机号码'
					},
					'info.wechat': {
						type: 'string',
						required: true,
						message: '请输入微信号',
						trigger: ['blur', 'change']
					},
					'info.password': {
						type: 'string',
						required: true,
						message: '请输入登录密码',
						trigger: ['blur', 'change'],
						min: 6,
						max: 20,
						message: '密码长度需在6到20字符之间'
					},
					'info.confirm_password': [{
						type: 'string',
						required: true,
						message: '请确认登录密码',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							if (value !== this.model.info.password) {
								return false;
							}
							return true;
						},
						message: '两次输入的密码不一致',
						trigger: ['blur']
					}],
					'info.bio': {
						type: 'string',
						required: true,
						message: '请输入店铺简介',
						trigger: ['blur', 'change']
					},
					'info.description': {
						type: 'string',
						required: true,
						message: '请输入店铺描述',
						trigger: ['blur', 'change']
					},
					'info.state_text': {
						type: 'string',
						required: true,
						message: '请选择企业类型',
						trigger: ['blur', 'change']
					},
					'info.area_text': {
						type: 'string',
						required: true,
						message: '请选择店铺区域',
						trigger: ['blur', 'change']
					},
					'info.avatar': {
						required: true,
						message: '请上传店铺LOGO',
						trigger: 'change'
					},
					'info.image': {
						required: true,
						message: '请上传营业执照照片',
						trigger: 'change'
					},
					'info.authorization_images': {
						required: this.authState,
						message: '请上传授权证书',
						trigger: 'change'
					}
				},
				itemStyle: "padding: 28rpx 0rpx;"
			};
		},
		computed: {
			buttonCustomStyle() {
				return {
					width: '90%',
					borderRadius: '20rpx'
				}
			}
		},
		onLoad() {
			this.JoinInfo();
		},
		methods: {
			openStatePicker() {
				this.$refs.statePicker.open();
			},
			successSelectAddress(address) {
				this.model.info.area_id = address.areaid;
				this.model.info.area_text = address.formatted_address;
			},
			btnAddressClick() {
				this.$refs.wanlAddress.show()
			},
			stateConfirm(e) {
				if (e.value[0] == '授权代理') {
					this.authState = true;
					this.model.info.state = 1;
				} else {
					this.authState = false;
					this.model.info.state = 2;
				}
				this.model.info.state_text = e.value[0];
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event.name)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			uploadFilePromise(url, name) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: '/wanlshop.common/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let result = JSON.parse(res.data);
							let url = result.data.url;
							if (name == 1) {
								this.model.info.avatar = url;
							} else if (name == 2) {
								this.model.info.image = url;

								// 识别营业执照
								uni.request({
									url: '/wanlshop/user/getLicenseInfoFromImage',
									method: 'POST',
									data: {
										imageUrl: result.data.fullurl
									},
									success: (ocrRes) => {
										this.model.info.name = ocrRes.res.data.companyName;
										this.model.info.number = ocrRes.res.data
											.creditCode;
										this.model.info.legal_person = ocrRes.res.data
											.legalPerson;
									},
									complete: (ocrRes) => {
										this.$wanlshop.msg(ocrRes.res.msg);
									}
								});
							} else if (name == 3) {
								if (this.model.info.authorization_images !== '') {
									this.model.info.authorization_images += ',' + url;
								} else {
									this.model.info.authorization_images = url;
								}
							}

							setTimeout(() => {
								resolve(result.data)
							}, 1000)
						}
					});
				})
			},
			// 提交
			submit() {
				uni.showLoading({
					title: "提交中..."
				});
				let that = this;
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form.validate().then(res => {
					that.submitJoin();
				}).catch(errors => {
					that.$wanlshop.msg(errors[0].message, 2000, true, 'none');
				})
			},
			async submitJoin() {
				await uni.request({
					url: '/wanlshop.shop/submitJoin',
					method: 'POST',
					data: {
						...this.model.info
					},
					success: (res) => {
						uni.hideLoading();
						if (res.res.code == 1) {
							this.$wanlshop.msg('申请成功！', 2000, true, 'success');
							setTimeout(() => {
								this.$wanlshop.to("/pages/enter/progress/progress");
							}, 2000);
						} else {
							this.$wanlshop.msg(res.res.msg, 2000, true);
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '加载失败，请检查网络'
						});
					},
					complete: (res) => {
						if (res.res.code == 0) {
							this.$wanlshop.msg(res.res.msg, 2000, true);
						}
					}
				});
			},

			async JoinInfo() {
				await uni.request({
					url: '/wanlshop.shop/getJoinInfo',
					method: 'POST',
					data: {},
					success: (res) => {
						uni.hideLoading();
						if (res.res.code == 1) {
							let data = res.res.data;
							if (data.step.step == -1) {
								Object.keys(data).forEach(key => {
									if (this.model.info.hasOwnProperty(key)) {
										if (key == 'state_text') {
											this.model.info.state_text = this.stateList[0][data
												.state - 1
											];
										} else {
											this.model.info[key] = data[key];
										}
									}
								});
								if (data.state == 1) {
									this.authState = true;
								}
								this.fileList1.push({
									status: 'success',
									thumb: this.$wanlshop.config('url') + data.avatar,
									type: 'image'
								})
								this.fileList2.push({
									status: 'success',
									thumb: this.$wanlshop.config('url') + data.image,
									type: 'image'
								})
								const authImgs = (data.authorization_images || '').split(',');
								authImgs.forEach(url => {
									if (url) {
										this.fileList3.push({
											status: 'success',
											thumb: this.$wanlshop.config('url') + url,
											type: 'image'
										});
									}
								});
							} else if (data.step.step == 1) {
								if (data.step.license.length > 0) {
									this.model.info.name = data.step.license.companyName;
									this.model.info.number = data.step.license.creditCode;
									this.model.info.legal_person = data.step.license.legalPerson;
									this.model.info.image = data.step.license.licenseImage;
									this.fileList2.push({
										status: 'success',
										thumb: data.step.license.licenseImage,
										type: 'image'
									});
								}
							}
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '加载失败，请检查网络'
						});
					}
				});
			},
		}
	}
</script>

<style>
	.uv-form-item {}
</style>

<style lang="scss" scoped>
	.container {
		margin: 0rpx 32rpx 32rpx 32rpx;
	}

	.form {
		border-radius: 10rpx;
		padding: 20rpx 0rpx;

		.label {
			color: #1A1A1A;
			font-size: 28rpx;
			padding: 20rpx 0rpx 10rpx 4rpx;
		}

		.item {
			background: #FFFFFF;
			padding: 0rpx 28rpx;
			margin: 12rpx 0rpx 26rpx 0rpx;
			border-radius: 10rpx;
		}
	}

	.btn {
		padding: 50rpx 0rpx;
		width: 100%;
		display: flex;
		justify-content: center;
	}
</style>